package servlet;

import com.alibaba.fastjson.JSON;
import entity.MemoType;
import service.MemoTypeService;
import service.impl.MemoTypeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/MemoTypeServlet")
public class MemoTypeServlet extends HttpServlet {
    ResultSet rs;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter out = resp.getWriter();
        MemoTypeService service = new MemoTypeServiceImpl();

        String opr = req.getParameter("opr");
        if (opr.equals("list")){
            List<MemoType> list = new ArrayList<>();
            int uid = Integer.parseInt(req.getParameter("uid"));
            rs = service.selectMemoTypes(uid);

            MemoType memoType = new MemoType(0,"全部",uid);
            list.add(memoType);
            try {
                while (rs.next()){
                    int mtid = rs.getInt("mtid");
                    String mtname = rs.getString("mtname");
                    uid = rs.getInt("uid");
                    memoType = new MemoType(mtid,mtname,uid);
                    list.add(memoType);
                }
                memoType = new MemoType(list.size(),"+",uid);
                list.add(memoType);

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            String listJson = JSON.toJSONString(list);
            out.print(listJson);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
